import { reactive, onMounted } from 'vue'
import { useMessage } from 'naive-ui'
import type { tableInfoState, configState, delInfoState } from '@/types/hooks'
export function useApi(config: configState) {
  const tableInfo = reactive<tableInfoState>({
    showSearch: true,
    listLoading: false,
    total: 0,
    tableData: [],
    queryForm: {
      pageNo: 1,
      pageSize: 10
    },
    pageSizes: [10, 20, 30, 40],
    checkedRowKeys: []
  })
  if (config.initForm) {
    tableInfo.queryForm = {
      ...tableInfo.queryForm,
      ...config.initForm
    }
  }
  if (config.isPaging === undefined) {
    config.isPaging = true
  }
  const pageChange = (page: number) => {
    tableInfo.queryForm.pageNo = page
    fetchData()
  }
  const sizeChange = (size: number) => {
    tableInfo.queryForm.pageSize = size
    tableInfo.queryForm.pageNo = 1
    fetchData()
  }

  const fetchData = async () => {
    tableInfo.listLoading = true
    const { data }: any = await config.getData(tableInfo.queryForm)
    if (config.isPaging) {
      if (config?.dataMap) {
        config?.dataMap(data.data)
      }
      tableInfo.tableData = data.data
      tableInfo.total = Math.ceil(data.total / tableInfo.queryForm.pageSize)
    } else {
      if (config?.dataMap) {
        config?.dataMap(data)
      }
      tableInfo.tableData = data
    }
    tableInfo.listLoading = false
    if (config?.fetchOver) {
      config?.fetchOver()
    }
  }

  const queryData = () => {
    tableInfo.queryForm.pageNo = 1
    fetchData()
  }
  /**
   *  添加编辑
   * */
  const handAdd = (row?: any) => {
    if (config?.addRef) {
      config.addRef.value.open(row || null)
    }
  }
  /**
   *  删除
   * */
  const toast = useMessage()
  const delInfo: delInfoState = reactive({
    delLoading: false,
    row: {
      id: ''
    }
  })
  const handDel = (row?: any) => {
    if (row) {
      delInfo.row = row
    } else {
      if (tableInfo.checkedRowKeys.length === 0) {
        toast.warning('请选择要删除的数据')
        return
      }
      delete delInfo.row
    }
    config.delRef.value.open()
  }
  const delConfirm = async () => {
    if (config?.delData) {
      const ids = delInfo?.row ? [delInfo.row.id] : tableInfo.checkedRowKeys
      delInfo.delLoading = true
      const { code, message } = await config.delData({
        ids
      })
      delInfo.delLoading = false
      if (code !== 200) {
        config.delRef.value.closeLoading()
        toast.error(message)
        return
      }
      config.delRef.value.close()
      toast.success('删除成功')
      fetchData()
    }
  }

  onMounted(() => {
    if (config.isRequest || config.isRequest === undefined) {
      queryData()
    }
  })

  return {
    tableInfo,
    delInfo,
    pageChange,
    sizeChange,
    fetchData,
    queryData,
    handAdd,
    delConfirm,
    handDel
  }
}
